import React, { useState, useEffect, useMemo } from 'react';
import * as echarts from 'echarts';

import {
  fetchsync_util,
  addkey_for_mxdata,
  convertISODateTimeToYYYYMMDDHHMMSS,
  view_item_util,
  openNotification_util,
  convertISODateTimeToYYYYMMDDHHMMSS_notutc,
} from '../util/util.js'
import { SaveOutlined, StopOutlined, CheckSquareOutlined } from '@ant-design/icons';
import moment from 'moment'
import 'moment/locale/zh-cn'
import { use_bj_initcolmun, use_xmbj_initcolmun, use_zb_view_column_initformdata, use_jb_gys_initcolmun, use_jjh_jj_initcolmun, use_jjh_tb_initcolmun } from './use_zbzx_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import CountdownFlipCard from './countdownFlipCard.js';
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js';
import { Button, Input, InputNumber, Modal, Popconfirm, Tabs, Tag, Badge } from 'antd';
import Upload_fj_hooks from '../newmes/upload_fj_hooks.js';
import { useLatest } from 'ahooks';
const { CheckableTag } = Tag;
import Xm_zbmx_hook from './xm_zbmx_hook.js';

const Xm_zb_from = () => {
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
  })
  const [isloading, setisloading] = useState(true)
  const [wlmxdata, setwlmxdata] = useState([])
  const [gysmxdata, setgysmxdata] = useState([])
  const [bjmxdata, setbjmxdata] = useState([])
  const [zzmxdata, setzzmxdata] = useState([])
  const [wlPrecisionMap, setWlPrecisionMap] = useState({})
  const [wlmxcolums, setwlmxcolums] = useState(JSON.parse(storage.pre_xm_zb_item).data.zbxs == "竞价" ? use_jjh_jj_initcolmun() : use_jjh_tb_initcolmun())
  const [gysmxcolums, setgysmxcolums] = useState(use_jb_gys_initcolmun)
  const [bjcolums, setbjcolums] = useState(use_xmbj_initcolmun)
  // const [zbcolums, setzbcolums] = useState(use_zb_column_initformdata)
  const [bjjg, setBjjg] = useState(0)
  const [bjfj, setBjfj] = useState("")
  const [formdata, setformdata] = useState({})
  const [wldata, setWldata] = useState() //当前报价的物料数据
  const formdataRef = useLatest(formdata)
  const [djs, setDjs] = useState(0) //倒计时
  const [modalOpen, setModalOpen] = useState(false)
  const [bjlc, setBjlc] = useState(1) //当前报价轮次
  const [supplierMap, setSupplierMap] = useState({}) //供应商名称映射

  const [selectedRows, setselectedRows] = useState("") //当前选中的明细行数据
  const [selectedRowKeys, setselectedRowKeys] = useState([]) //当前选中的明细行key
  const [gysselectedRows, setgysselectedRows] = useState("") //当前选中的供应商行数据
  const [gysselectedRowKeys, setgysselectedRowKeys] = useState([]) //当前选中的供应商行key

  const [ifshowchart, setifshowchart] = useState(false) //是否显示报价趋势图
  const [ifshow_tt, setifshow_tt] = useState(false) //是否显示淘汰
  const [ifshow_tt_gys, setifshow_tt_gys] = useState(false) //是否显示淘汰供应商
  const [ttyy, setTtyy] = useState("") //淘汰原因
  const [gysdata, setGysdata] = useState("") //供应商数据
  const [initStatus, setInitStatus] = useState(false) //初始化状态
  const bjmxdataRef = useLatest(bjmxdata)
  const initStatusRef = useLatest(initStatus)
  const [activeKey, setactiveKey] = useState(1)
  /**
   * 强制刷新明细表 用于特殊场景
   */
  const [switche, setswitche] = useState(true);
  const forceupdate = () => { setswitche(false) }
  useEffect(() => { switche ? "1" : setswitche(true) }, [switche])

  const init = async () => {
    setisloading(true)
    setdynDatasObject({ ...dynDatasObject })
    setisloading(false)
  }

  const getDecimalPlaces = (num) => {
    if (Math.floor(num) === num) return 0;
    const str = num.toString();
    if (str.indexOf('.') !== -1 && str.indexOf('e-') === -1) {
      return str.split('.')[1].length;
    } else if (str.indexOf('e-') !== -1) {
      const parts = str.split('e-');
      return parseInt(parts[1], 10);
    }
    return 0;
  }

  const ensureNumeric = (value) => {
    if (value === null || value === undefined || value === '') {
      return 0;
    }
    if (typeof value === 'number') {
      return value;
    }
    const parsed = parseFloat(String(value).replace(/,/g, ''));
    return Number.isNaN(parsed) ? 0 : parsed;
  }

  const isPercentMode = (value) => {
    if (value === null || value === undefined) return false;
    return String(value).includes('%');
  }

  const getBaseAmountForPrecision = (config = {}) => {
    if (!config) return 0;
    if (config.dqbj !== undefined && config.dqbj !== null && config.dqbj !== '') {
      return ensureNumeric(config.dqbj);
    }
    if (config.qsj !== undefined && config.qsj !== null && config.qsj !== '') {
      return ensureNumeric(config.qsj);
    }
    if (config.qsj_dj !== undefined && config.qsj_dj !== null && config.qsj_dj !== '') {
      return ensureNumeric(config.qsj_dj);
    }
    return 0;
  }

  const getPricePrecision = (config = {}) => {
    if (!config) return 2;
    const blje = config.blje;
    if (isPercentMode(blje)) {
      const baseAmount = getBaseAmountForPrecision(config);
      const baseDecimals = getDecimalPlaces(baseAmount);
      return Math.max(baseDecimals + 2, 2);
    }
    if (blje !== null && blje !== undefined && blje !== '') {
      const diff = ensureNumeric(blje);
      if (!Number.isNaN(diff)) {
        return getDecimalPlaces(diff);
      }
    }
    const baseAmount = getBaseAmountForPrecision(config);
    const baseDecimals = getDecimalPlaces(baseAmount);
    return Math.max(baseDecimals, 2);
  }

  const normalizePriceByRule = (price, config = {}) => {
    if (price === null || price === undefined || price === '') {
      return price;
    }
    const numericPrice = ensureNumeric(price);
    if (Number.isNaN(numericPrice)) {
      return price;
    }
    const precision = getPricePrecision(config);
    return Number(numericPrice.toFixed(precision));
  }

  const formatPriceByRule = (price, config = {}) => {
    if (price === null || price === undefined || price === '') {
      return '';
    }
    const numericPrice = ensureNumeric(price);
    if (Number.isNaN(numericPrice)) {
      return '';
    }
    const precision = getPricePrecision(config);
    return numericPrice.toFixed(precision);
  }

  const getConfigForRecord = (record) => {
    if (!record) return {};
    if (record.bjwlmxid && wlPrecisionMap[record.bjwlmxid]) {
      return wlPrecisionMap[record.bjwlmxid];
    }
    if (record.id && wlPrecisionMap[record.id]) {
      return wlPrecisionMap[record.id];
    }
    if (record.wlmxid && wlPrecisionMap[record.wlmxid]) {
      return wlPrecisionMap[record.wlmxid];
    }
    return record;
  }

  const formatColumnsWithPriceRule = (columns = []) => {
    return columns.map(col => {
      if (!col || !col.dataIndex) return col;
      if (col.dataIndex === 'blbj' || col.dataIndex === 'dqbj') {
        const originalRender = col.render
        return {
          ...col,
          render: (value, record, index) => {
            const formattedValue = formatPriceByRule(value, getConfigForRecord(record))
            if (typeof originalRender === 'function') {
              return originalRender(formattedValue, record, index)
            }
            return formattedValue
          }
        }
      }
      return col;
    });
  }

  // 供应商名称转换
  // const transformSuppliers = (data) => {
  //   // 创建一个空的映射对象
  //   const supplierMap = {};
  //   // 创建一个字母表，用于生成供应商名称的后缀
  //   const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  //   let supplierIndex = 0;

  //   // 遍历原始数组，生成映射
  //   data.forEach(supplier => {
  //     if (!supplierMap[supplier.gysmc]) {
  //       // 生成新的供应商名称
  //       const supplierName = `供应商${alphabet[supplierIndex % alphabet.length]}`;
  //       supplierMap[supplier.gysmc] = supplierName;
  //       supplierIndex++;
  //     }
  //   });
  //   setSupplierMap(supplierMap)
  // }

  const { setnowroute, collapsed } = useStore();
  //加载主表数据
  const loadformdata = async (data) => {
    let rtdata = await fetchsync_util("/admin/zbzx/query_jb_byid", 'POST', { data }, "json")
    let newformdata = rtdata.resultdata.formdata
    newformdata.dqlkssj = newformdata.dqlkssj ? convertISODateTimeToYYYYMMDDHHMMSS(newformdata.dqlkssj) : ""
    newformdata.dqljzsj = newformdata.dqljzsj ? convertISODateTimeToYYYYMMDDHHMMSS(newformdata.dqljzsj) : ""
    setDjs(newformdata.djs)
    // if (newformdata.jjzt == '竞价中') {
    //   //获取倒计时 秒数
    //   let djs = (new Date(newformdata.dqljzsj).getTime() - new Date().getTime()) / 1000
    //   setDjs(djs.toFixed(0))
    // }
    // else if (newformdata.jjzt == '待竞价') {
    //   //获取倒计时 秒数
    //   let djs = (new Date(newformdata.dqlkssj).getTime() - new Date().getTime()) / 1000
    //   // console.log(djs, "一开始的倒计时");
    //   setDjs(djs.toFixed(0))
    // }
    // else if (newformdata.jjzt == '竞价休息') {
    //   let djs = (new Date(newformdata.dqljzsj).getTime() + (newformdata.mljg * 60 * 1000) - new Date().getTime()) / 1000
    //   // console.log(djs, "竞价休息的倒计时");
    //   setDjs(djs.toFixed(0))
    // }
    if (!initStatusRef.current) {
      setBjlc(newformdata.dqlc)
      setselectedRows(rtdata.resultdata.wlmxdata)
      setselectedRowKeys(rtdata.resultdata.wlmxdata.map((item) => item.id))
    }
    setInitStatus(true)
    setformdata({ ...newformdata })
    const wlConfigMap = {}
    rtdata.resultdata.wlmxdata.forEach(item => {
      wlConfigMap[item.id] = item
    })
    setWlPrecisionMap(wlConfigMap)
    setwlmxdata(addkey_for_mxdata(rtdata.resultdata.wlmxdata))
    setgysmxdata(addkey_for_mxdata(rtdata.resultdata.gysmxdata))

    setbjmxdata(addkey_for_mxdata(rtdata.resultdata.bjmxdata.map((item) => {
      const config = wlConfigMap[item.bjwlmxid] || {}
      const normalizedPrice = normalizePriceByRule(item.blbj, config)
      return {
        ...item,
        blbj: normalizedPrice,
        bjsj: item.bjsj ? convertISODateTimeToYYYYMMDDHHMMSS(item.bjsj) : ""
      }
    })))
    // if (rtdata.resultdata.ifzz) {
    //   setzbcolums(use_zb_view_column_initformdata)
    // }
    // else {
    //   setzbcolums(use_zb_column_initformdata)
    // }
    // transformSuppliers(rtdata.resultdata.zzmxdata)
    setzzmxdata(addkey_for_mxdata(rtdata.resultdata.zzmxdata.map((item) => {
      const config = wlConfigMap[item.bjwlmxid] || wlConfigMap[item.wlmxid] || item
      return {
        ...item,
        bjsj: item.bjsj ? convertISODateTimeToYYYYMMDDHHMMSS(item.bjsj) : "",
        zbsl: item.sl ? item.sl : "",
        blbj: normalizePriceByRule(item.blbj, config)
      }
    })))
  }

  // 页面进入加载数据
  useEffect(() => {
    loadformdata(JSON.parse(storage.pre_xm_zb_item).data)
    setisloading(false)
    let a = setInterval(() => {
      loadformdata(JSON.parse(storage.pre_xm_zb_item).data)
    }, 10000)
    return () => {
      clearInterval(a)
    }
  }, [])

  // 处理倒计时结束
  const handleDjsEnd = async () => {
    await loadformdata(JSON.parse(storage.pre_xm_zb_item).data)
    if (formdata.xmzt != "竞价结束") {
      setBjlc(formdataRef.current.dqlc)
    }
    // let formdata = formdataRef.current
    // // 竞价结束
    // if (formdata.dqlc < formdata.jjls_bj && (formdata.xmzt == "竞价中" || formdata.xmzt == "待竞价")) {
    //   if (formdata.jjzt == "竞价休息") {
    //     //当前轮次加一
    //     let dqlc = formdata.dqlc + 1
    //     setBjlc(dqlc)
    //     // 计算下一轮开始时间
    //     let xylkssj = new Date(formdata.dqljzsj).getTime() + formdata.mljg * 60 * 1000
    //     let dqlkssj = new Date(xylkssj)
    //     console.log(dqlkssj, "dqlkssj");

    //     // 计算下一轮结束时间
    //     let xyljzsj = new Date(xylkssj).getTime() + formdata.mlcx * 60 * 1000
    //     let dqljzsj = new Date(xyljzsj)
    //     console.log(dqljzsj, "dqljzsj");
    //     // 计算倒计时
    //     let djs = (dqljzsj.getTime() - new Date().getTime()) / 1000
    //     console.log(djs, "djs");
    //     setDjs(djs.toFixed(0))
    //     let jjzt = "竞价中"
    //     // 更新竞价数据
    //     let newformdata = { ...formdata, dqlc, jjzt, dqlkssj: convertISODateTimeToYYYYMMDDHHMMSS_notutc(dqlkssj), dqljzsj: convertISODateTimeToYYYYMMDDHHMMSS_notutc(dqljzsj) }
    //     setformdata(newformdata)
    //   }
    //   else if (formdata.jjzt == "竞价中") {

    //     //当前轮次加一
    //     let dqlc = formdata.dqlc
    //     let jjzt = "竞价休息"
    //     // 计算倒计时
    //     let djs = formdata.mljg * 60
    //     // 更新竞价数据
    //     let newformdata = { ...formdata, dqlc, jjzt }
    //     setDjs(djs.toFixed(0))
    //     setformdata(newformdata)
    //   }
    //   else if (formdata.jjzt == "待竞价") {
    //     let jjzt = "竞价中"
    //     // 计算倒计时
    //     let djs = (new Date(formdata.dqljzsj).getTime() - new Date().getTime()) / 1000
    //     setDjs(djs.toFixed(0))
    //     let newformdata = { ...formdata, jjzt }
    //     setformdata(newformdata)
    //   }
    // }
    // // 竞价进行中
    // else if (formdata.dqlc == formdata.jjls_bj && formdata.xmzt == '竞价中') {
    //   let jjzt = "竞价结束"
    //   let newformdata = { ...formdata, jjzt }
    //   setformdata(newformdata)
    // }
  }


  // ... existing code ...
  const initchartdrcctj = async (wldata) => {
    let bjmxdata = bjmxdataRef.current;
    var chartDom = document.getElementById('chart_bjqs');
    var myChart = echarts.init(chartDom);
    console.log(wldata, "wldata");
    // 按供应商分组数据
    let supplierGroups = {};
    bjmxdata.filter(item => item.bjwlmxid === wldata?.id).forEach(item => {
      if (!supplierGroups[item.gysmc]) {
        supplierGroups[item.gysmc] = [];
      }
      supplierGroups[item.gysmc].push(item);
    });

    // 获取所有轮次
    let allRounds = [...new Set(bjmxdata.map(item => item.bjlc))].sort((a, b) => a - b);
    let xData = allRounds.map(round => `第${round}轮`);

    // 准备系列数据
    let series = Object.entries(supplierGroups).map(([gysmc, data], index) => {
      // 为每个轮次准备数据,如果没有报价则为null
      let seriesData = allRounds.map(round => {
        let roundData = data.find(item => item.bjlc === round);
        return roundData ? roundData.blbj : null;
      });

      // 生成随机颜色
      let color = `rgb(${Math.random() * 200 + 55},${Math.random() * 200 + 55},${Math.random() * 200 + 55})`;

      return {
        name: gysmc, // 使用供应商映射名称
        type: 'line',
        data: seriesData,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: color
        },
        lineStyle: {
          width: 2
        }
      };
    });
    wldata
    var option = {
      title: {
        text: `供应商报价趋势图-${wldata?.wlmc}`,
        left: 'center',
        textStyle: {
          color: '#333',
          fontSize: 18
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let result = params[0].axisValue + '<br/>';
          params.forEach(param => {
            if (param.value !== null) {
              result += `${param.seriesName}: ${param.value ? param.value + '元' : '该轮没报价'}<br/>`;
            }
          });
          return result;
        }
      },
      legend: {
        data: Object.keys(supplierGroups).map(gysmc => gysmc),
        bottom: 0
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          color: '#666'
        }
      },
      yAxis: {
        type: 'value',
        name: '报价金额(元)',
        nameTextStyle: {
          color: '#666'
        },
        axisLabel: {
          color: '#666',
          formatter: '{value}'
        }
      },
      series: series,
      grid: {
        left: '10%',
        right: '5%',
        bottom: '15%',
        top: '15%'
      }
    };

    option && myChart.setOption(option);
  };
  // ... existing code ...
  //淘汰单一物料
  const handle_ttgys_wl = async () => {
    await fetchsync_util("/admin/zbzx/ttgys_wl", 'POST', { gysdata, ttyy }, "json")
    openNotification_util(`${gysdata.wlmc}淘汰成功`)
    setifshow_tt(false)
    setTtyy("")
    await loadformdata(JSON.parse(storage.pre_xm_zb_item).data)
  }
  //淘汰供应商
  const handle_ttgys = async () => {
    await fetchsync_util("/admin/zbzx/ttgys", 'POST', { gysdata: [{ ...gysdata }], ttyy: ttyy }, "json")
    openNotification_util(`${gysdata.gysmc}淘汰成功`)
    setifshow_tt_gys(false)
    setTtyy("")
    await loadformdata(JSON.parse(storage.pre_xm_zb_item).data)
  }


  // 竞价终止
  const handle_jjzz = async () => {
    await fetchsync_util("/admin/zbzx/jjzz", 'POST', { id: formdataRef.current.id, }, "json")
    openNotification_util("竞价终止成功")
    setDjs(0)
    await loadformdata(JSON.parse(storage.pre_xm_zb_item).data)
  }

  // 中标确认
  const handle_zbsz = async () => {
    if (formdataRef.current.xmzt != "竞价结束") {
      openNotification_util("请先确保竞价状态为竞价结束")
      return
    }
    let rtdata = await fetchsync_util("/admin/zbzx/save_zbsz", 'POST', { zzmxdata }, "json")
    openNotification_util(rtdata.rtmessage)
    await loadformdata(JSON.parse(storage.pre_xm_zb_item).data)
  }

  const Title_item = (props) => {
    return (
      <div
        style={{
          height: "3vh", position: "relative", width: "100%", textIndent: "0.5rem", color: "#666666", lineHeight: "3vh",
          fontSize: "14px", fontWeight: "500", textAlign: "left", borderLeftStyle: "solid", borderWidth: "0.3rem", borderColor: "#a91f24",
          marginBottom: "0.5vh", letterSpacing: "0.05rem", marginTop: "1vh"
        }}>
        {props.title}
      </div>
    )
  }

  const Title_item_content = (props) => {
    return (
      <div style={{
        fontSize: "1vw", fontWeight: "500", color: "#a91f24", marginLeft: "1vw", position: "relative", width: "100%",
        height: "4vh", lineHeight: "4vh"
      }}>
        <div style={{ color: "#858585", position: "absolute", left: "0", width: "40%" }}>{props.title}：</div>
        <div style={{ color: "black", position: "absolute", right: "0", width: "60%", ...props.styles }}>
          {props.content}
        </div>
      </div>
    )
  }

  const wlColumnsFormatted = useMemo(() => formatColumnsWithPriceRule(wlmxcolums), [wlmxcolums, wlPrecisionMap])
  const gysColumnsFormatted = useMemo(() => formatColumnsWithPriceRule(gysmxcolums), [gysmxcolums, wlPrecisionMap])
  const bjColumnsFormatted = useMemo(() => formatColumnsWithPriceRule(bjcolums), [bjcolums, wlPrecisionMap])

  return (
    <div
      style={{
        height: "94%",
        backgroundColor: `#F1F1F1`,
        right: "1%",
        top: "5.9vh",
        overflow: "hidden",
        backgroundSize: "100% 100%",
        width: collapsed ? "94%" : "84%",
        position: "absolute",
        color: "white",
        fontSize: "0.8rem"
      }}
    >
      <Modal
        open={ifshowchart}
        width="80%"
        bodyStyle={{ height: "80vh" }}
        onCancel={() => { setifshowchart(false) }}
        footer={null}
      >
        <div id="chart_bjqs" style={{ width: "100%", height: "100%" }}></div>
      </Modal>

      {/* 淘汰供应商 Modal */}
      <Modal
        title="淘汰供应商"
        open={ifshow_tt_gys}
        onOk={handle_ttgys}
        onCancel={() => {
          setifshow_tt_gys(false)
          setTtyy("")
        }}
        okText="确认淘汰"
        cancelText="取消"
        okButtonProps={{ danger: true }}
      >
        <div style={{ marginBottom: "1rem" }}>
          <p><strong>供应商名称：</strong>{gysdata?.gysmc}</p>
        </div>
        <div>
          <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "600" }}>
            淘汰原因：
          </label>
          <Input.TextArea
            value={ttyy}
            onChange={(e) => setTtyy(e.target.value)}
            placeholder="请输入淘汰原因..."
            rows={4}
            maxLength={200}
            showCount
          />
        </div>
      </Modal>

      {/* 淘汰单一物料 Modal */}
      <Modal
        title="淘汰物料报价"
        open={ifshow_tt}
        onOk={handle_ttgys_wl}
        onCancel={() => {
          setifshow_tt(false)
          setTtyy("")
        }}
        okText="确认淘汰"
        cancelText="取消"
        okButtonProps={{ danger: true }}
      >
        <div style={{ marginBottom: "1rem" }}>
          <p><strong>供应商名称：</strong>{gysdata?.gysmc}</p>
          <p><strong>物料名称：</strong>{gysdata?.wlmc}</p>
          <p><strong>物料编码：</strong>{gysdata?.wlbm}</p>
          <p><strong>规格型号：</strong>{gysdata?.ggxh}</p>
        </div>
        <div>
          <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "600" }}>
            淘汰原因：
          </label>
          <Input.TextArea
            value={ttyy}
            onChange={(e) => setTtyy(e.target.value)}
            placeholder="请输入淘汰该物料报价的原因..."
            rows={4}
            maxLength={200}
            showCount
          />
        </div>
      </Modal>
      {/* 工具栏 */}
      <div style={styles.kshcontainer}>
        <div style={{
          width: "100%", height: "6%", position: "sticky", top: "0", left: "1%", backgroundColor: "white", color: "black", display: "flex",
          borderRadius: "10px", zIndex: 100, borderBottom: "2px solid #a91f24"
        }}>
          <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            工具栏
          </div>
          <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
            {formdata.jjzt == "竞价中" && <Button type="default" style={styles.button_style} onClick={() => { handle_jjzz() }}>
              <StopOutlined />竞价终止</Button>}
          </div>
        </div>
        {/* 主内容区：上下布局 */}
        <div style={{ width: "100%", height: "95%", backgroundColor: "#f1f3f4", display: "flex", flexDirection: "column" }}>
          {/* 上方：左右分栏 */}
          <div style={{ width: "100%", display: "flex", flexWrap: "nowrap", minWidth: 0, marginBottom: "2vh" }} data-section="main-flex">
            {/* 左侧倒计时卡片 */}
            <div style={{ width: "30%", minWidth: 260, maxWidth: 400, flexShrink: 0 }} data-section="left-card" data-card="true">
              {<Title_item title="轮次信息" />}
              <div className={formdata.jjzt == '竞价中' ? 'fly_border' : ""}
                style={{
                  width: "100%", height: "32vh", borderRadius: "10px", backgroundColor: "white", marginBottom: "1vh", marginTop: "1vh", textAlign: "center", position: 'relative',
                  boxShadow: formdata.jjzt == '竞价中' ?
                    "0 0 10px #25bf2f" : formdata.jjzt == '竞价休息' ? "0 0 10px #1890FF" :
                      "0 0 10px #ff1010",
                }}>
                {formdata.zbxs == '自由竞价' ?
                  <div style={{ fontSize: "1vw", fontWeight: "400", color: "#b6b6b6", marginTop: "1.3vh", position: "relative" }}>
                    <div style={{ position: "relative",paddingTop: "2vh" }}>
                      <span style={{ fontWeight: "400", fontSize: "1vw", }}>竞价持续</span> <span style={{ color: "#a91f24", fontWeight: "600", fontSize: "1.3vw" }}>{formdata?.mlcx}</span>分钟
                    </div>
                  </div> :
                  <div style={{ fontSize: "1vw", fontWeight: "400", color: "#b6b6b6", marginTop: "1.3vh", position: "relative" }}>
                    <div style={{ position: "relative", paddingTop: "2vh", }}>
                      共设置 <span style={{ color: "#000000", fontWeight: "600", fontSize: "1.3vw", }}>{formdata?.jjls_bj}</span> 轮竞价
                      &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
                      当前进行 <span style={{ color: "#a91f24", fontWeight: "600", fontSize: "1.3vw" }}>{formdata?.dqlc}</span> 轮
                    </div>
                    <div style={{ position: "relative" }}>
                      <span style={{ fontWeight: "400", fontSize: "1vw", }}>每轮持续</span> <span style={{ color: "#a91f24", fontWeight: "600", fontSize: "1.3vw" }}>{formdata?.mlcx}</span>分钟
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
                      <span style={{ fontWeight: "400", fontSize: "1vw", }}>每轮间隔</span> <span style={{ color: "#000000", fontWeight: "600", fontSize: "1.3vw" }}>{formdata?.mljg}</span>分钟
                    </div>
                  </div>}
                <div style={{ fontSize: "1.2vw", fontWeight: "600", color: "#a91f24", marginTop: "3vh" }}>
                  <CountdownFlipCard initialSeconds={djs} onEnd={() => { handleDjsEnd() }} />
                </div>
                {/* 项目信息补充显示 */}
                <div style={{ fontSize: "1vw", fontWeight: "400", marginTop: "2vh", position: "relative", color: "#b6b6b6", left: "1rem" }}>
                  <div style={{ display: "flex", alignItems: "center", marginBottom: "10px" }}>
                    <span>项目名称</span>
                    <span style={{ color: "#000000", fontWeight: "400", marginLeft: "0.5vw" }}>{formdata?.xmmc}</span>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-start", width: "100%" }}>
                    <span>当前状态</span>
                    <span style={{
                      marginLeft: "20px", color:
                        formdata.jjzt == '竞价中' ? "#25bf2f" :
                          formdata.jjzt == '竞价休息' ? "#1890FF" :
                            "#ff1010", fontWeight: "400"
                    }}>●</span>
                    <span style={{ marginLeft: "10px" }}>{formdata.jjzt}</span>
                    <span style={{ marginLeft: "30px" }}>竞价规则</span>
                    <span style={{ marginLeft: "20px", color: "#000000", fontWeight: "400" }}>{formdata?.jjgz}</span>
                  </div>
                </div>
              </div>
            </div>
            {/* 右侧Tabs区 */}
            <div style={{ width: "67%", minWidth: 0, marginLeft: "3%", flex: 1,paddingRight: "1.5vw" }} data-section="right-card" data-card="true">
              {<Title_item title="竞价行&供应商信息" />}
              <div style={{ width: "100%", height: "32vh", position: 'relative', borderRadius: "10px", backgroundColor: "white", marginBottom: "1vh", marginTop: "1vh", padding: "1vh 0", overflowX: "auto", minWidth: "600px" }} data-table-container="true">
                <Tabs className='task-tabs'>
                  <Tabs.TabPane tab=" 竞价行信息" key="1">
                    <Custom_table_hooks_config
                      tabledata={wlmxdata} tablecolnum={wlColumnsFormatted}
                      width={"100%"}
                      sfdoubleclick="false" ifhiddencchangeselecttype="true"
                      selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
                      defaultPageSize={3}
                      bordered
                      showCz
                      noSearch
                      renderCz={(data) => {
                        return <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                          <Button
                            onClick={() => {
                              setifshowchart(true);
                              setTimeout(() => {
                                initchartdrcctj(data);
                              }, 1000);
                            }}
                            style={{
                              fontSize: '0.6rem', backgroundColor: "#f0fdfd",
                              fontWeight: "600", color: "#090c94"
                            }} size="small" >查看报价趋势图</Button>

                        </div>
                      }}
                      handleselectson={(selectedRows, selectedRowKeys) => {
                        setselectedRows(selectedRows)
                        setselectedRowKeys(selectedRowKeys)
                      }}
                    />
                  </Tabs.TabPane>
                  <Tabs.TabPane tab=" 供应商信息" key="2">
                    <Custom_table_hooks_config
                      tabledata={gysmxdata} tablecolnum={gysColumnsFormatted}
                      width={"100%"}
                      sfdoubleclick="false" ifhiddencchangeselecttype="true"
                      selectedRows={gysselectedRows} selectedRowKeys={gysselectedRowKeys}
                      defaultPageSize={3}
                      bordered
                      showCz
                      noSearch
                      renderCz={(data) => {
                        return <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                          <Button
                            onClick={() => {
                              setGysdata(data)
                              setifshow_tt_gys(true)
                            }}
                            disabled={formdata.jjzt == "竞价结束"}
                            style={{
                              fontSize: '0.6rem', backgroundColor: "#f0fdfd",
                              fontWeight: "600", color: "#090c94"
                            }} size="small" >淘汰</Button>

                        </div>
                      }}
                      handleselectson={(selectedRows, selectedRowKeys) => {
                        setgysselectedRows(selectedRows)
                        setgysselectedRowKeys(selectedRowKeys)
                      }}
                    />
                  </Tabs.TabPane>
                </Tabs>
              </div>
            </div>
          </div>
          {/* 下方：下方：报价明细 */}
          <Title_item title="报价明细" />
          <div style={{ width: "100%", height: "calc(100% - 46vh)", position: 'relative', borderRadius: "10px", paddingRight: "2vw",backgroundColor: "white", marginBottom: "1vh", marginTop: "1vh", padding: "1vh 0", overflowX: "auto", minWidth: "600px" }} data-section="bid-detail" data-table-container="true">
            {formdata.zbxs === "竞价" || (formdata.zbxs !== "自由竞价" && formdata.jjls > 0) ? (
              <Tabs activeKey={bjlc?.toString() ?? 1} onChange={(key) => { setBjlc(key) }} className='task-tabs'>
                {Array.from({ length: formdata.jjls }, (_, i) => (
                  <Tabs.TabPane tab={<span>第{i + 1}轮报价</span>} key={i + 1}>
                    <Custom_table_hooks_config
                      tabledata={addkey_for_mxdata(bjmxdata.filter((item) => item.bjlc === i + 1 && selectedRows.some((item2) => item2.wlmc == item.wlmc)))}
                      tablecolnum={bjColumnsFormatted}
                      width={"100%"}
                      sfdoubleclick="false"
                      ifhiddencchangeselecttype="true"
                      defaultPageSize={5}
                      supplierMap={supplierMap}
                      showCz
                      renderCz={(data) => {
                        return <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                          <Button
                            onClick={() => {
                              setGysdata(data)
                              setifshow_tt(true)
                            }}
                            disabled={formdata.jjzt == "竞价结束" || data.ttyy}
                            style={{
                              fontSize: '0.6rem', backgroundColor: "#f0fdfd",
                              fontWeight: "600", color: "#090c94"
                            }} size="small" >淘汰</Button>

                      </div>
                    }}
                      rowClassName={(record) => {
                        return record.ttyy ? "my-table-pink-red" : ""
                      }}
                      bordered
                    />
                  </Tabs.TabPane>
                ))}
              </Tabs>
            ) : null}
            {formdata.zbxs === "自由竞价" && (
              <Tabs className='task-tabs' defaultActiveKey={activeKey} onChange={(key) => setactiveKey(key)}>
                {wlmxdata.map(wlmx => (
                  <Tabs.TabPane tab={wlmx.wlmc} key={wlmx.wlmc}>
                    <Custom_table_hooks_config
                      tabledata={bjmxdata.filter(item => item.wlmc === wlmx.wlmc).map((item, index) => {
                        item.blpm = index + 1
                        item.xuhao = index + 1
                        return item
                      })}
                      tablecolnum={bjColumnsFormatted}
                      width={"100%"}
                      ifhiddencchangeselecttype="true"
                      defaultPageSize={5}
                      supplierMap={supplierMap}
                      showCz
                      renderCz={(data) => {
                        return <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                          <Button
                            onClick={() => {
                              setGysdata(data)
                              setifshow_tt(true)
                            }}
                            disabled={formdata.jjzt == "竞价结束" || data.ttyy}
                            style={{
                              fontSize: '0.6rem', backgroundColor: "#f0fdfd",
                              fontWeight: "600", color: "#090c94"
                            }} size="small" >淘汰</Button>
                      </div>
                    }}
                      bordered
                    />
                  </Tabs.TabPane>
                ))}
              </Tabs>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}


export default Xm_zb_from
var styles = {
  kshcontainer: {
    width: "98%", position: "absolute", top: "1%", left: "1%", backgroundColor: "white", color: "black", height: "99%",
    borderRadius: "10px"
  },
  button_style: {
    width: "9vw", height: '2vw', fontSize: "0.7rem", borderRadius: "5px", margin: "0 0.5vw", marginTop: "0.1vw"
  }
}